
package com.starshineworks.util.actions;

import com.starshineworks.entities.*;
import com.starshineworks.util.Util;

import java.util.Map;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ActionLogin extends Action {
        
    @Override
    public boolean perform(HttpServletRequest  request, 
                           HttpServletResponse resp,
                           HttpServlet         serv, 
                           boolean             isMultiPart)
    {        
        Map<String,String[]> map = request.getParameterMap();
        String name = map.get("_username")[0];
        String pass = map.get("_password")[0];
        List<EntityE> list = EntityE.retrieve(new UserE(name));
        if (!list.isEmpty()) {
            UserE user = (UserE) list.get(0);
            if (user != null) {
                if (user._password.equals(Util.hide(pass))) {
                    HttpSession sess = request.getSession();
                    sess.setAttribute("uId", user._id);
                    sess.setAttribute("username", name);
                    sess.setAttribute("fullName", user.fullName());
                    return true;
                }
            }
        }
        return false;
    }
    
    @Override
    public String getNextPage() {
        return "User";
    }
    
    @Override
    public String getError() {
        return "Userid or password are not recognized. Did you register?";
    }

}
